import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
import Cars from '../views/Cars.vue'
import AIAssistant from '../views/AIAssistant.vue'
import Stats from '../views/Stats.vue'
import Profile from '../views/Profile.vue'
import Login from '../views/Login.vue'
import Register from '../views/Register.vue'

// 导入认证API
import { authAPI } from '../api/auth.js'

const routes = [
  { path: '/', name: 'Home', component: Home },
  { path: '/cars', name: 'Cars', component: Cars },
  { path: '/ai-assistant', name: 'AIAssistant', component: AIAssistant },
  { path: '/stats', name: 'Stats', component: Stats },
  { path: '/profile', name: 'Profile', component: Profile },
  { path: '/login', name: 'Login', component: Login },
  { path: '/register', name: 'Register', component: Register }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 添加路由守卫
router.beforeEach((to, from, next) => {
  // 需要认证的路由路径
  const protectedRoutes = ['/ai-assistant', '/stats', '/profile']
  
  // 检查目标路由是否需要认证
  if (protectedRoutes.includes(to.path)) {
    // 检查用户是否已登录
    if (authAPI.checkLoginStatus()) {
      // 已登录，允许访问
      next()
    } else {
      // 未登录，阻止访问并显示提示（在组件中处理）
      next(false)
      // 触发全局事件，通知组件显示登录提示对话框
      window.dispatchEvent(new CustomEvent('login-required', { detail: { targetRoute: to.path } }))
    }
  } else {
    // 不需要认证的路由，直接访问
    next()
  }
})

export default router